<!-- 文件管理 -->
<template>
  <a-card :bordered="false" class="card-area">
    <!-- 查询条件 -->
    <div>
      <a-form-model :model="searchForm" ref="searchForm">
        <a-row>
          <a-col :span="9">
            <a-form-model-item prop='updateTime' label='修改时间' :labelCol="{span: 5}" :wrapperCol="{span: 12, offset: 1}">
              <a-range-picker v-model="searchForm.updateTime" @change="onChange" allow-clear/>
            </a-form-model-item>
          </a-col>
          <a-col :span="9">
            <a-form-model-item label='文件名称' prop='fileName' :labelCol="{span: 5}" :wrapperCol="{span: 12, offset: 1}">
              <a-input v-model="searchForm.fileName" placeholder="请输入文件名称" allow-clear/>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <!-- 操作按钮 -->
    <a-space>
      <a-button @click="handleAdd">
        <a-icon type="folder-add" />新建文件夹
      </a-button>
      <a-button @click="batchMove">移动</a-button>
      <a-button @click="batchDel" type="danger">删除</a-button>
    </a-space>
    <div style="margin: 16px 0">
      <a-breadcrumb>
        <a-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
          <a @click="allFile(index)">{{ item.name }}</a>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <!-- 表格部分 -->
    <div>
      <a-table :data-source="dataSource" :columns="columns" :rowKey="(record, index) => {return record.name}"
        :pagination="false" :row-selection="{selectedRowKeys: selectedRowKeys, onChange: rowSelection}">
        <template slot="name" slot-scope="text, record">
          <editable-cell :text="text" :showEdit="record.isDir" :isEdit="isEdits"
            @clickDJ="DJi(record.isDir, record.name)" @change="onCellChange(record.fullName, $event)"
            @closeItem="closeIpt"/>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a v-if="record.isDir !== true" @click="downFile(record.name)">下载</a>
          <a @click="moveFile(record)">移动</a>
          <a-popconfirm title="是否删除这条数据?" @confirm="() => onDelete(record)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <!-- 树状弹框 -->
    <a-modal title="移动到..." :visible="visible" :confirm-loading="confirmLoading" :keyboard="false"
             :closable="false" @ok="handleOk" @cancel="handleCancel" :maskClosable="false">
      <div>
        <a-tree v-model="checkedKeys" :show-icon='true' :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent"
          :selected-keys="selectedKeys" :tree-data="treeData" @expand="onExpand" @select="onSelect">
          <a-icon slot="folder" type="folder" theme="filled" class="icon-color"/>
        </a-tree>
      </div>
    </a-modal>
  </a-card>
</template>
<script>
import EditableCell from './EditableCell'

export default {
  name: 'FileManagement',
  components: {
    EditableCell
  },
  data () {
    return {
      searchForm: {
        fileName: '',
        startDate: '',
        endDate: ''
      },
      expandedKeys: [],
      autoExpandParent: false,
      checkedKeys: [],
      selectedKeys: [],
      fileTitle: '',
      treeData: [
        {
          title: '全部文件',
          key: '/',
          slots: {icon: 'folder'},
          children: []
        }
      ],
      breadcrumbList: [
        {
          name: '全部文件',
          urls: '/'
        }
      ],
      columns: [
        {
          title: '文件名称',
          dataIndex: 'name',
          width: '30%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          align: 'center'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center'
        },
        {
          title: '大小',
          dataIndex: 'fileSize',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          align: 'center'
        }
      ],
      dataSource: [],
      isDir: true,
      paramss: {
        currPath: '/'
      },
      isEdits: false,
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      confirmLoading: false
    }
  },
  watch: {},
  methods: {
    onChange (val, obj) {
      this.searchForm.startDate = obj[0]
      this.searchForm.endDate = obj[1]
    },
    search () {
      this.crumbsFirst()
    },
    reset () {
      this.$refs.searchForm.resetFields()
      this.crumbsFirst()
    },
    getData () {
      this.$get('fileManager/getFileList', this.paramss).then((res) => {
        this.dataSource = res.data
      })
    },
    rowSelection (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onCellChange (fullName, targetName) {
      this.$put('fileManager/renameFileOrDirectory', {
        fullName: fullName,
        targetName: targetName
      }).then((res) => {
        if (res.data.status) {
          this.isEdits = false
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    closeIpt () {
      this.isEdits = false
      this.getData()
    },
    onDelete (name) {
      let arr = []
      arr.push(name.fullName)
      this.$delete('fileManager/deleteFileOrDirectory', {
        fullNamesList: arr
      }).then((res) => {
        if (res.data.status) {
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    downFile (name) {
      this.$download('fileManager/downloadFile', {
        fullName: name
      }, name).then(res => {
        if (res.data.status) {
          this.$message.success(res.data.message)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 初始化文件夹列表
    initMoveFileView () {
      this.treeData[0].children = [{}]
      this.expandedKeys = []
      this.visible = true
    },
    moveFile (obj) {
      // 先清空，防止事先选择造成干扰
      this.selectedRows = []
      this.selectedRowKeys = []
      this.selectedRows.push(obj)
      this.initMoveFileView()
    },
    handleAdd () {
      this.isEdits = true
      const { dataSource } = this
      const newData = {
        name: `新建文件夹`,
        updateTime: '',
        createTime: '',
        fileSize: ''
      }
      this.dataSource = [...dataSource, newData]
      this.$put('fileManager/createDirectory', {
        currPath: this.paramss.currPath,
        directoryName: '新建文件夹'
      }).then((res) => {
        if (res.data.status) {
          this.isEdits = false
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    batchDel () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择需要删除的记录')
      } else {
        let arr = []
        this.selectedRows.forEach(item => {
          arr.push(item.fullName)
        })
        this.$delete('fileManager/deleteFileOrDirectory', {
          fullNamesList: arr
        }).then((res) => {
          if (res.data.status) {
            this.$message.success(res.data.message)
            this.selectedRows = []
            this.selectedRowKeys = []
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    batchMove () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择需要移动的文件/文件夹')
      } else {
        this.initMoveFileView()
      }
    },
    onSelect (selectedKeys, info) {
      this.fileTitle = info.node.dataRef.title
      this.selectedKeys = selectedKeys
    },
    onExpand (expandedKeys, info) {
      if (info.expanded) {
        let targetPath = expandedKeys[expandedKeys.length - 1]
        info.node.dataRef.children = []
        this.$get('fileManager/getFileList', {
          currPath: targetPath
        }).then((res) => {
          let newArr = res.data.filter((obj) => obj.isDir === true)
          for (let index = 0; index < newArr.length; index++) {
            const ele = newArr[index]
            info.node.dataRef.children.push({
              title: ele.name,
              key: ele.fullName,
              slots: {icon: 'folder'},
              children: [{}]
            })
          }
        })
      }

      this.expandedKeys = expandedKeys
    },
    handleOk () {
      let that = this
      if (that.fileTitle === '') {
        this.$message.error('需要移动的数据不能为空,请选择需要移动到的位置')
      } else {
        let newArr = []
        that.selectedRows.forEach(item => {
          newArr.push(item.fullName)
        })
        that.$put('fileManager/moveFileOrDirectory', {
          fullNamesList: newArr,
          targetPath: that.selectedKeys[0]
        }).then((res) => {
          if (res.data.status) {
            that.$message.success(res.data.message)
            this.selectedRows = []
            this.selectedRowKeys = []
            that.getData()
            that.visible = false
          } else {
            that.$message.error(res.data.message)
          }
        })
      }
    },
    handleCancel () {
      this.visible = false
    },
    // 点击地址展开文件夹
    DJi (tORf, name) {
      if (tORf === false) {
      } else {
        this.breadcrumbList.push({
          name: name,
          urls: '/' + name
        })
        let urlName = []
        this.breadcrumbList.forEach((item) => {
          urlName.push(item.urls)
        })
        this.paramss.currPath = urlName.slice(1).join('')
        this.getData()
      }
    },
    // 点击地址返回上一层文件
    allFile (index) {
      if (index === 0) {
        this.crumbsFirst()
      } else {
        let pathb = this.breadcrumbList.slice(0, index + 1)
        this.breadcrumbList = pathb
        let urlName = []
        this.breadcrumbList.forEach((item) => {
          urlName.push(item.urls)
        })
        let pathName = urlName.slice(1).join('')
        this.paramss.currPath = pathName
        this.getData()
      }
    },
    // 面包屑初始化
    crumbsFirst () {
      let patha = this.breadcrumbList.slice(0, 1)
      this.breadcrumbList = patha
      if (this.breadcrumbList.length === 1) {
        this.paramss.currPath = '/'
      }
      this.getData()
    }
  },
  mounted () {
    this.getData()
  }
}
</script>
<style lang='less' scoped>
</style>
